package cn.hbu.zlfw.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author 王鹏伟<1   2   2   3   4   4   3   2   8   9   @   qq.com>
 * @ClassName: FileHandingUtil
 * @Description: 文件处理工具类
 * @date 2017年12月13日 下午10:07:51
 * @vsersion:v1.0
 */
public class FileHandingUtil {
    /**
     * @return String 返回"时间目录_UUID_文件名"形式的文件名，当上传的文件为空文件时返回null
     * @throws
     * @Title: uploadFile
     * @Description: 文件上传工具类，处理多个上传文件
     */
    public static String[] uploadFileList(MultipartFile[] uploadFileList, HttpServletRequest request) {
        ArrayList<String> result = new ArrayList<String>();
        for (MultipartFile multipartFile : uploadFileList) {
            String fileName = uploadFile(multipartFile, request);
            if (fileName != null) result.add(fileName);
        }
        return result.toArray(new String[result.size()]);
    }

    /**
     * @return String 返回"时间目录_UUID_文件名"形式的文件名，当上传的文件为空文件时返回null
     * @throws
     * @Title: uploadFile
     * @Description: 文件上传工具类，处理单个上传文件
     */
    public static String uploadFile(MultipartFile uploadFile, HttpServletRequest request) {
        String time_uuid_filename = null;
        if (null == uploadFile) {
            return null;
        }
        String originalFilename = uploadFile.getOriginalFilename();
        if (null == originalFilename || "" == originalFilename) {    //防止空文件
            return null;
        }
        //文件名设置成"时间目录_UUID_文件名"形式：防止文件名字重复
        time_uuid_filename = Utility.getFormatDate() + "_" + Utility.getUUID() + "_" + originalFilename;
        String targetDirectory = "C://zlfwUploadfiles/" + Utility.getFormatDate();
        File file = new File(targetDirectory, time_uuid_filename);
        if (!file.exists()) {
            file.mkdirs();
        }
        //转存文件
        try {
            uploadFile.transferTo(file);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return time_uuid_filename;
    }

    /**
     * @return Boolean 文件存在时进行下载返回true，文件不存在时返回false
     * @throws
     * @Title: downloadFile
     * @Description: 文件下载工具类，只处理一个文件
     */
    public static Boolean downloadFile(String timeuuidfilename, HttpServletResponse response, HttpServletRequest request) {

        String storeDirectory = "C://zlfwUploadfiles/" + timeuuidfilename.split("_")[0];
        File file = new File(storeDirectory + File.separator + timeuuidfilename);
        if (file.exists()) {
            InputStream in = null;
            OutputStream out = null;
            try {
                String primaryfilename = timeuuidfilename.substring(timeuuidfilename.lastIndexOf("_") + 1);
                System.out.println(primaryfilename);
                in = new FileInputStream(file);
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                    primaryfilename = URLEncoder.encode(primaryfilename, "UTF-8");
                } else {
                    primaryfilename = new String(primaryfilename.getBytes(), "ISO-8859-1");
                    System.out.println(primaryfilename);
                }

                response.setHeader("Content-Disposition", "attachment;filename=\"" + primaryfilename + "\"");
                out = response.getOutputStream();
                int len = -1;
                byte bytes[] = new byte[1024];
                while ((len = in.read(bytes)) != -1) {
                    out.write(bytes, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }//end finally
            return true;
        } else {
            return false;
        }
    }
}
